package com.pomelo.chat.controller;

import com.pomelo.chat.domain.Chat;
import com.pomelo.chat.service.ChatGPTService;
import com.pomelo.chat.service.ChatService;
import com.pomelo.chat.util.AjaxResult;
import com.pomelo.chat.util.Common;
import com.pomelo.chat.util.Question;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/open-ai")
public class ChatController {

    Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Resource
    private ChatGPTService chatGPTService;

    @Resource
    private ChatService chatService;


    @GetMapping("/token")
    public AjaxResult getToken() {
        return AjaxResult.success(Common.createUUID());
    }

    /**
     *  开始对话
     * @param question 问题实体
     * @param token 携带的token
     * @param bindingResult 响应结果
     * @param request 请求实体
     */
    @PostMapping("/ask")
    public AjaxResult chatGPT3(@RequestBody Question question,
                               @RequestHeader(name = "token", required = false) String token,
                               BindingResult bindingResult,
                               HttpServletRequest request) {
        String ip;
        if (request.getHeader("X-Forwarded-For") != null) {
            ip = request.getHeader("X-Forwarded-For");
        } else if (request.getHeader("X-Real-IP") != null) {
            ip = request.getHeader("X-Real-IP");
        } else {
            ip = "0:0:0:0:0:0:0:1".equals(request.getRemoteAddr()) ? "127.0.0.1" : request.getRemoteAddr();
        }
        if (bindingResult.hasErrors()) {
            return AjaxResult.failure(bindingResult.getAllErrors().get(0).toString());
        }
        Chat chat = chatGPTService.askGPT3(question, ip);
        return AjaxResult.success(chat);
    }

    /**
     * 查询历史记录
     * @param username 用户名
     * @param pageSize 查询记录条数
     * @param pageNum 查询记录页数
     */
    @GetMapping("/history")
    public AjaxResult history(String username, Integer pageSize, Integer pageNum) {
        if (username == null) {
            username = "GaoYang";
        }
        List<Chat> chats = chatService.getPage(username,pageSize, pageNum);
        return chats == null ? AjaxResult.failure("查询失败") : AjaxResult.success(chats);
    }

}
